package com.xd.common.utils;

import cn.hutool.core.collection.CollUtil;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.List;

/**
 * @author huboxin
 * @title: PathMatchingUtil
 * @projectName bk
 * @description: 路径匹配工具类
 * @date 2020/7/2416:47
 */
public class PathMatchingUtil {

    /**
     * 路径规则匹配器
     */
    public static final PathMatcher PATH_MATCHER = new AntPathMatcher();


    /**
     * 校验路径是否符合规则
     * @param lookupPath 需要校验的路径
     * @param excludePatterns 需要拦截的路径
     * @param includePatterns 拦截规则
     * @return 是否拦截
     */
    public static boolean matches(String lookupPath, List<String> excludePatterns,List<String> includePatterns) {
        if (!org.springframework.util.ObjectUtils.isEmpty(excludePatterns)) {
            for (String pattern : excludePatterns) {
                if (PathMatchingUtil.PATH_MATCHER.match(pattern, lookupPath)) {
                    return false;
                }
            }
        }
        if (org.springframework.util.ObjectUtils.isEmpty(includePatterns)) {
            return true;
        }
        for (String pattern : includePatterns) {
            if (PathMatchingUtil.PATH_MATCHER.match(pattern, lookupPath)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 校验路径是否符合规则
     * @param lookupPath 需要校验的路径
     * @param excludePatterns 需要拦截的路径
     * @return true 不包含再匹配规则里, false包含
     */
    public static boolean matches(String lookupPath, List<String> excludePatterns) {
        return matches(lookupPath, excludePatterns, CollUtil.newArrayList("/**"));
    }
}
